import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { In, Repository } from 'typeorm';
import { Dept } from 'src/entities/system/dept.entity';
import { Role } from 'src/entities/system/role.entity';
import { UserAdmin } from 'src/entities/user/user-admin.entity';
import { BusinessException } from '@/common/exceptions/business.filter';
import { User } from 'src/entities/user/user.entity';
import { Menu } from '@/entities/menus/menu.entity';
import { listToTree } from '@/utils/utils';
import { ToolsService } from '@/service/tools/tools.service';
@Injectable()
export class SystemService {
  constructor(
    @InjectRepository(Dept)
    private readonly deptRepository: Repository<Dept>,
    @InjectRepository(Role)
    private readonly roleRepository: Repository<Role>,
    @InjectRepository(UserAdmin)
    private readonly userAdminRepository: Repository<UserAdmin>,
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
    @InjectRepository(Menu)
    private readonly menuRepository: Repository<Menu>,
    private toolsService: ToolsService,
  ) {}
  // 查找路由
  async getRoutes(user: any) {
    const { user_id } = user;
    try {
      let adminUserInfo = await this.userAdminRepository.findOne({
        where: { id: user_id },
      });
      // 如果没有把use表同步到user-admin中，且用户为游客
      if (!adminUserInfo) {
        let findUser = await this.userRepository.findOne({
          where: { user_id: user_id },
        });
        if (findUser) {
          await this.userAdminRepository.save({
            id: user_id,
            name: findUser.name,
            phone: findUser.phone,
          });
        }
        return [];
      } else {
        if (adminUserInfo.roleIds) {
          let roleIds = adminUserInfo.roleIds.split(',');
          let menuIds = [] as string[];
          const roles = await this.roleRepository.findBy({ id: In(roleIds) });
          menuIds = Array.from(
            new Set(
              roles
                .filter((item) => item.menuIds)
                .flatMap((role) => role.menuIds.split(',')),
            ),
          );
          let menus = await this.menuRepository.find({
            where: {
              id: In(menuIds),
              visible: 1,
              type: In([1, 2]), //目录
            },
          });
          return menus;
        }
        return '';
      }
    } catch (error) {
      throw new BusinessException(error.message);
    }
  }
  async getRoutes1(user: any) {
    try {
      let res = await this.menuRepository.find({
        where: {
          visible: 1,
          type: In([1, 2]), //目录
        },
      });
      return listToTree(res, this._initRoutes);
    } catch (error) {
      throw new BusinessException(error.message);
    }
  }
  // 获取部门列表
  async getDeptList() {
    try {
      let deptList = await this.deptRepository.find();
      if (!deptList) {
        throw new BusinessException('error');
      }
      return listToTree(deptList, (item: any) => {
        return {
          label: item.name,
          value: item.id,
          parentId: item.parentId,
          id: item.id,
        };
      });
    } catch (error) {
      throw new BusinessException(error.message);
    }
  }
  _initRoutes(item: any) {
    let route = {
      parentId: item.parentId,
      id: item.id,
      meta: {
        alwaysShow: item.alwaysShow ? true : false,
        hidden: item.visible ? false : true,
        icon: item.icon,
        keepAlive: item.keepAlive ? true : false,
        params: null,
        title: item.name,
      },
      name: item.routeName,
      path: item.routePath,
      component: item.parentId == 0 ? 'Layout' : item.component,
    } as any;
    if (item.redirect) {
      route.redirect = item.redirect;
    }
    return route;
  }
  // 新增用户
  async addUser(body: any) {
    return this.toolsService._addEntity(this.userAdminRepository, body);
  }
  // 修改用户
  async updateUser(body: any) {
    return this.toolsService._updateEntity(this.userAdminRepository, body);
  }
  // 删除用户
  async deleteUser(id: string) {
    return this.toolsService._deleteEntity(this.userAdminRepository, id);
  }
  // 查询用户
  async getUser() {
    return this.toolsService._findEntity(this.userAdminRepository);
  }

  // 新增部门
  async addDept(body: any) {
    return this.toolsService._addEntity(this.deptRepository, body);
  }
  // 修改部门
  async updateDept(body: any) {
    return this.toolsService._updateEntity(this.deptRepository, body);
  }
  // 删除部门
  async deleteDept(id: string) {
    return this.toolsService._deleteEntity(this.deptRepository, id);
  }
  // 查询部门
  async getDept() {
    return this.toolsService._findEntity(this.deptRepository);
  }

  // 新增角色
  async addRole(body: any) {
    return this.toolsService._addEntity(this.roleRepository, body);
  }
  // 修改角色
  async updateRole(body: any) {
    return this.toolsService._updateEntity(this.roleRepository, body);
  }
  // 删除角色
  async deleteRole(id: string) {
    return this.toolsService._deleteEntity(this.roleRepository, id);
  }
  // 查询角色
  async getRole() {
    return this.toolsService._findEntity(this.roleRepository);
  }
}
